import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  Tag,
  message,
  Row,
  Col,
  Statistic,
  Typography,
  Badge,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  SendOutlined,
  FileTextOutlined,
  RobotOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';

const { Title, Text } = Typography;
const { Option } = Select;
const { Search, TextArea } = Input;

// 内容数据接口
interface ContentItem {
  id: string;
  title: string;
  contentType: 'ARTICLE' | 'QA' | 'PRODUCT_DESC' | 'COMPANY_INTRO';
  keywords: string[];
  content: string;
  status: 'DRAFT' | 'PUBLISHED' | 'OPTIMIZING' | 'ARCHIVED';
  aiOptimized: boolean;
  viewCount: number;
  createdAt: string;
}

// 内容类型配置
const contentTypeConfig = {
  ARTICLE: { label: '文章', color: 'blue' },
  QA: { label: '问答', color: 'green' },
  PRODUCT_DESC: { label: '产品描述', color: 'orange' },
  COMPANY_INTRO: { label: '公司介绍', color: 'purple' },
};

// 状态配置
const statusConfig = {
  DRAFT: { color: 'default', text: '草稿' },
  PUBLISHED: { color: 'success', text: '已发布' },
  OPTIMIZING: { color: 'processing', text: '优化中' },
  ARCHIVED: { color: 'warning', text: '已归档' },
};

const ContentManagement: React.FC = () => {
  const [contents, setContents] = useState<ContentItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingContent, setEditingContent] = useState<ContentItem | null>(null);
  const [searchText, setSearchText] = useState('');
  const [form] = Form.useForm();

  // 模拟数据
  const mockContents: ContentItem[] = [
    {
      id: '1',
      title: 'AI智能优化技术在企业中的应用',
      contentType: 'ARTICLE',
      keywords: ['AI智能优化', '企业应用', '技术创新'],
      content: '随着人工智能技术的快速发展，AI智能优化已成为企业数字化转型的重要工具...',
      status: 'PUBLISHED',
      aiOptimized: true,
      viewCount: 1520,
      createdAt: '2024-01-15T10:30:00Z',
    },
    {
      id: '2',
      title: '机器学习算法选择指南',
      contentType: 'QA',
      keywords: ['机器学习', '算法选择'],
      content: 'Q: 如何选择合适的机器学习算法？\nA: 选择机器学习算法需要考虑数据类型...',
      status: 'OPTIMIZING',
      aiOptimized: false,
      viewCount: 890,
      createdAt: '2024-01-16T09:15:00Z',
    },
    {
      id: '3',
      title: '智能电商推荐系统产品介绍',
      contentType: 'PRODUCT_DESC',
      keywords: ['电商推荐', '智能系统'],
      content: '我们的智能电商推荐系统采用先进的深度学习技术...',
      status: 'DRAFT',
      aiOptimized: true,
      viewCount: 0,
      createdAt: '2024-01-17T16:45:00Z',
    },
  ];

  useEffect(() => {
    loadContents();
  }, []);

  const loadContents = async () => {
    setLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 1000));
      setContents(mockContents);
    } catch (error) {
      message.error('加载内容列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 统计数据
  const stats = {
    total: contents.length,
    published: contents.filter(c => c.status === 'PUBLISHED').length,
    draft: contents.filter(c => c.status === 'DRAFT').length,
    aiOptimized: contents.filter(c => c.aiOptimized).length,
  };

  // 表格列定义
  const columns: ColumnsType<ContentItem> = [
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      width: 300,
      render: (text: string, record) => (
        <div>
          <Text strong style={{ color: '#1890ff' }}>{text}</Text>
          <div style={{ marginTop: 4 }}>
            {record.keywords.map(keyword => (
              <Tag key={keyword} color="blue">
                {keyword}
              </Tag>
            ))}
          </div>
        </div>
      ),
    },
    {
      title: '类型',
      dataIndex: 'contentType',
      key: 'contentType',
      width: 100,
      render: (type: string) => {
        const config = contentTypeConfig[type as keyof typeof contentTypeConfig];
        return <Tag color={config.color}>{config.label}</Tag>;
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => {
        const config = statusConfig[status as keyof typeof statusConfig];
        return <Badge status={config.color as any} text={config.text} />;
      },
    },
    {
      title: '浏览量',
      dataIndex: 'viewCount',
      key: 'viewCount',
      width: 100,
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 120,
      render: (date: string) => new Date(date).toLocaleDateString('zh-CN'),
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space>
          <Button size="small" icon={<EyeOutlined />}>
            预览
          </Button>
          <Button
            type="primary"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            danger
            size="small"
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const handleAdd = () => {
    setEditingContent(null);
    form.resetFields();
    setIsModalVisible(true);
  };

  const handleEdit = (content: ContentItem) => {
    setEditingContent(content);
    form.setFieldsValue({
      ...content,
      keywords: content.keywords.join(', '),
    });
    setIsModalVisible(true);
  };

  const handleDelete = async (id: string) => {
    try {
      setContents(prev => prev.filter(c => c.id !== id));
      message.success('删除成功');
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleSave = async (values: any) => {
    try {
      const keywords = values.keywords.split(',').map((k: string) => k.trim()).filter(Boolean);
      
      if (editingContent) {
        setContents(prev => prev.map(c => 
          c.id === editingContent.id ? { ...c, ...values, keywords } : c
        ));
        message.success('更新成功');
      } else {
        const newContent: ContentItem = {
          id: Date.now().toString(),
          ...values,
          keywords,
          status: 'DRAFT' as const,
          aiOptimized: false,
          viewCount: 0,
          createdAt: new Date().toISOString(),
        };
        setContents(prev => [newContent, ...prev]);
        message.success('添加成功');
      }
      setIsModalVisible(false);
    } catch (error) {
      message.error('保存失败');
    }
  };

  return (
    <div>
      <Title level={2}>内容管理</Title>
      
      {/* 统计概览 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col xs={24} sm={6}>
          <Card>
            <Statistic
              title="内容总数"
              value={stats.total}
              prefix={<FileTextOutlined />}
            />
          </Card>
        </Col>
        <Col xs={24} sm={6}>
          <Card>
            <Statistic
              title="已发布"
              value={stats.published}
              valueStyle={{ color: '#3f8600' }}
              prefix={<SendOutlined />}
            />
          </Card>
        </Col>
        <Col xs={24} sm={6}>
          <Card>
            <Statistic
              title="草稿"
              value={stats.draft}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={6}>
          <Card>
            <Statistic
              title="AI优化"
              value={stats.aiOptimized}
              valueStyle={{ color: '#52c41a' }}
              prefix={<RobotOutlined />}
            />
          </Card>
        </Col>
      </Row>

      {/* 操作工具栏 */}
      <Card style={{ marginBottom: 16 }}>
        <Row gutter={16} align="middle">
          <Col xs={24} sm={8}>
            <Search
              placeholder="搜索标题或关键词"
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
            />
          </Col>
          <Col xs={24} sm={16}>
            <Space>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={handleAdd}
              >
                添加内容
              </Button>
              <Button icon={<RobotOutlined />}>
                AI生成
              </Button>
            </Space>
          </Col>
        </Row>
      </Card>

      {/* 内容列表 */}
      <Card>
        <Table
          columns={columns}
          dataSource={contents}
          rowKey="id"
          loading={loading}
          pagination={{
            pageSize: 10,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
          }}
        />
      </Card>

      {/* 添加/编辑对话框 */}
      <Modal
        title={editingContent ? '编辑内容' : '添加内容'}
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
        width={800}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSave}
        >
          <Form.Item
            name="title"
            label="标题"
            rules={[{ required: true, message: '请输入标题' }]}
          >
            <Input placeholder="输入内容标题" />
          </Form.Item>
          
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="contentType"
                label="内容类型"
                rules={[{ required: true, message: '请选择内容类型' }]}
              >
                <Select placeholder="选择内容类型">
                  <Option value="ARTICLE">文章</Option>
                  <Option value="QA">问答</Option>
                  <Option value="PRODUCT_DESC">产品描述</Option>
                  <Option value="COMPANY_INTRO">公司介绍</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="keywords"
                label="关键词"
                rules={[{ required: true, message: '请输入关键词' }]}
              >
                <Input placeholder="用逗号分隔多个关键词" />
              </Form.Item>
            </Col>
          </Row>
          
          <Form.Item
            name="content"
            label="内容"
            rules={[{ required: true, message: '请输入内容' }]}
          >
            <TextArea rows={8} placeholder="输入具体内容" />
          </Form.Item>
          
          <Form.Item style={{ marginBottom: 0, textAlign: 'right' }}>
            <Space>
              <Button onClick={() => setIsModalVisible(false)}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                {editingContent ? '更新' : '添加'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default ContentManagement;